package com.example.view;

import com.example.config.GlobalConfig;
import com.example.entry.HeaderEntry;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;

import java.util.ArrayList;
import java.util.List;

public class GlobalConfigDialog extends Dialog<Void> {
    private VBox headersContainer;
    private VBox cookiesContainer;
    private List<HeaderEntry> headers = new ArrayList<>();
    private List<HeaderEntry> cookies = new ArrayList<>();
    private TextField headerNameField;
    private TextField headerValueField;
    private TextField cookieNameField;
    private TextField cookieValueField;

    public GlobalConfigDialog() {
        setTitle("全局配置");

        // 创建主布局
        TabPane tabPane = new TabPane();
        tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);

        // Headers 标签页
        Tab headersTab = new Tab("Headers");
        VBox headersBox = new VBox(10);
        headersBox.setPadding(new Insets(15));

        // 添加标题行和新增按钮
        HBox headerTitleBox = new HBox(10);
        headerTitleBox.setAlignment(Pos.CENTER_LEFT);
        Label headerLabel = new Label("全局请求头");
        Region headerSpacer = new Region();
        HBox.setHgrow(headerSpacer, Priority.ALWAYS);
        Button addHeaderButton = new Button("新增2");
        addHeaderButton.getStyleClass().add("add-button");
        headerTitleBox.getChildren().addAll(headerLabel, headerSpacer, addHeaderButton);

        // 添加滚动面板
        ScrollPane headersScrollPane = new ScrollPane();
        headersScrollPane.setFitToWidth(true);
        headersScrollPane.setStyle("-fx-background-color: transparent;");

        headersContainer = new VBox(5);
        headersScrollPane.setContent(headersContainer);
        headersBox.getChildren().addAll(headerTitleBox, headersScrollPane);
        headersTab.setContent(headersBox);

        // Cookies 标签页
        Tab cookiesTab = new Tab("Cookies");
        VBox cookiesBox = new VBox(10);
        cookiesBox.setPadding(new Insets(15));

        // 添加标题行和新增按钮
        HBox cookieTitleBox = new HBox(10);
        cookieTitleBox.setAlignment(Pos.CENTER_LEFT);
        Label cookieLabel = new Label("全局Cookies");
        Region cookieSpacer = new Region();
        HBox.setHgrow(cookieSpacer, Priority.ALWAYS);
        Button addCookieButton = new Button("新增1");
        addCookieButton.getStyleClass().add("add-button");
        cookieTitleBox.getChildren().addAll(cookieLabel, cookieSpacer, addCookieButton);

        // 添加滚动面板
        ScrollPane cookiesScrollPane = new ScrollPane();
        cookiesScrollPane.setFitToWidth(true);
        cookiesScrollPane.setStyle("-fx-background-color: transparent;");

        cookiesContainer = new VBox(5);
        cookiesScrollPane.setContent(cookiesContainer);
        cookiesBox.getChildren().addAll(cookieTitleBox, cookiesScrollPane);
        cookiesTab.setContent(cookiesBox);

        tabPane.getTabs().addAll(headersTab, cookiesTab);

        // 设置对话框大小
        DialogPane dialogPane = getDialogPane();
        dialogPane.setContent(tabPane);
        dialogPane.setPrefWidth(800);
        dialogPane.setPrefHeight(600);
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        // 加载现有配置
        loadExistingConfig();

        // 创建输入行
        VBox headerBox = new VBox(5);
        headerBox.getChildren().add(
            createInputRow(
                headerNameField = new TextField(),
                headerValueField = new TextField(),
                new Button(""),  // 空按钮占位
                this::addHeader
            )
        );
        headersContainer.getChildren().add(headerBox);

        VBox cookieBox = new VBox(5);
        cookieBox.getChildren().add(
            createInputRow(
                cookieNameField = new TextField(),
                cookieValueField = new TextField(),
                new Button(""),  // 空按钮占位
                this::addCookie
            )
        );
        cookiesContainer.getChildren().add(cookieBox);

        // 添加按钮事件
        addHeaderButton.setOnAction(e -> addHeader());
        addCookieButton.setOnAction(e -> addCookie());
    }

    private HBox createInputRow(TextField nameField, TextField valueField, Button addButton, Runnable addAction) {
        HBox row = new HBox(5);
        row.setAlignment(Pos.CENTER_LEFT);
        row.setPadding(new Insets(5));
        row.setStyle("-fx-background-color: #f6f8fa; -fx-background-radius: 6;");

        nameField.setPromptText("参数名");
        nameField.setPrefWidth(200);
        nameField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

        nameField.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ENTER && !nameField.getText().trim().isEmpty()) {
                Node currentFocus = nameField.getScene().getFocusOwner();
                addAction.run();
                if (currentFocus == nameField) {
                    nameField.requestFocus();
                } else if (currentFocus == valueField) {
                    valueField.requestFocus();
                }
            }
        });

        nameField.focusedProperty().addListener((obs, oldVal, newVal) -> {
            if (!newVal && !nameField.getText().trim().isEmpty()) {
                Node currentFocus = nameField.getScene().getFocusOwner();
                addAction.run();
                if (currentFocus == nameField) {
                    nameField.requestFocus();
                } else if (currentFocus == valueField) {
                    valueField.requestFocus();
                }
            }
        });

        valueField.setPromptText("参数值");
        HBox.setHgrow(valueField, Priority.ALWAYS);
        valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

        addButton.setVisible(false);
        addButton.setManaged(false);

        row.getChildren().addAll(nameField, valueField, addButton);
        return row;
    }

    private HBox createHeaderRow(HeaderEntry entry, List<HeaderEntry> list, VBox container) {
        HBox row = new HBox(5);
        row.setAlignment(Pos.CENTER_LEFT);
        row.setPadding(new Insets(5));
        row.setStyle("-fx-background-color: #f6f8fa; -fx-background-radius: 6;");

        TextField nameField = new TextField(entry.getName());
        nameField.setPrefWidth(200);
        nameField.textProperty().bindBidirectional(entry.nameProperty());
        nameField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

        TextField valueField = new TextField(entry.getValue());
        HBox.setHgrow(valueField, Priority.ALWAYS);
        valueField.textProperty().bindBidirectional(entry.valueProperty());
        valueField.setStyle("-fx-background-color: white; -fx-border-color: #e1e4e8; -fx-border-radius: 6;");

        Button deleteButton = new Button("删除");
        deleteButton.setOnAction(e -> {
            list.remove(entry);
            container.getChildren().remove(row);
        });
        deleteButton.getStyleClass().add("danger-button");

        row.getChildren().addAll(nameField, valueField, deleteButton);
        return row;
    }

    private void addHeader() {
        String name = headerNameField.getText().trim();
        String value = headerValueField.getText().trim();

        if (!name.isEmpty() && !value.isEmpty()) {
            HeaderEntry header = new HeaderEntry(name, value);
            header.setGlobal(true);
            headers.add(header);

            // 创建新的行并添加到列表中
            HBox row = createHeaderRow(header, headers, headersContainer);
            headersContainer.getChildren().add(headersContainer.getChildren().size() - 1, row);

            // 清空输入框
            headerNameField.clear();
            headerValueField.clear();
        }
    }

    private void addCookie() {
        String name = cookieNameField.getText().trim();
        String value = cookieValueField.getText().trim();

        if (!name.isEmpty()) {
            HeaderEntry cookie = new HeaderEntry(name, value);
            cookie.setGlobal(true);
            cookies.add(cookie);

            HBox row = createHeaderRow(cookie, cookies, cookiesContainer);
            cookiesContainer.getChildren().add(cookiesContainer.getChildren().size() - 1, row);

            cookieNameField.clear();
            cookieValueField.clear();
        }
    }

    private void loadExistingConfig() {
        // 加载现有的全局配置
        GlobalConfig config = GlobalConfig.getInstance();

        for (HeaderEntry header : config.getGlobalHeaders()) {
            if (header.getName() != null && !header.getName().trim().isEmpty()) {
                headers.add(header);
                HBox row = createHeaderRow(header, headers, headersContainer);
                headersContainer.getChildren().add(row);
            }
        }

        for (HeaderEntry cookie : config.getGlobalCookies()) {
            if (cookie.getName() != null && !cookie.getName().trim().isEmpty()) {
                cookies.add(cookie);
                HBox row = createHeaderRow(cookie, cookies, cookiesContainer);
                cookiesContainer.getChildren().add(row);
            }
        }
    }

}
